package com.focus.xyz.core.utils;

import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by cimon on 2016/3/22.
 */
public class ExcelUtil {

    private static XSSFSheet xssfSheet;
    private static XSSFWorkbook xssfWorkbook;
    private static XSSFCell xssfCell;
    private static XSSFRow xssfRow;
    private static final String caseDataFilePrefix = "data/";

    private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    public static void setExcelFile(String fileName) throws Exception{
        InputStream excelFile;
        try{
            excelFile = ResourceUtil.loadInputStreamFromClassPath(ConfigPropInfo.TEST_DATA_DIR + ConfigPropInfo.TEST_KEYWORD_FILE);
            xssfWorkbook = new XSSFWorkbook(excelFile);
        }catch (Exception e){
            throw (e);
        }
    }

    public static void setExcelFile(String fileName,String sheetName) throws Exception{
        InputStream excelFile;
        try{
            excelFile = ResourceUtil.loadInputStreamFromClassPath(ConfigPropInfo.TEST_DATA_DIR + ConfigPropInfo.TEST_KEYWORD_FILE);
            xssfWorkbook = new XSSFWorkbook(excelFile);
            xssfSheet = xssfWorkbook.getSheet(sheetName);
        }catch (Exception e){
            throw (e);
        }
    }

    public static String getCellData(int rowNum,int colNum) throws Exception{
        try{
            xssfCell = xssfSheet.getRow(rowNum).getCell(colNum);
            String cellData = xssfCell.getCellType() == XSSFCell.CELL_TYPE_STRING ? xssfCell.getStringCellValue() + "" : String.valueOf(Math.round(xssfCell.getNumericCellValue()));
            return cellData;
        }catch (Exception e){
            return "";
        }
    }

    public static void setCellData(String sheetName,int rowNum,int colNum,String result) throws Exception{
        try{
            xssfRow = xssfSheet.getRow(rowNum);
            xssfCell = xssfRow.getCell(colNum, Row.RETURN_BLANK_AS_NULL);
            if(xssfCell == null){
                xssfCell = xssfRow.createCell(colNum);
                xssfCell.setCellValue(result);
            }else{
                xssfCell.setCellValue(result);
            }
            FileOutputStream fileOut = new FileOutputStream("文件输出路径");
            //OutputStreamWriter osw = new OutputStreamWriter(fileOut,"UTF-8");
            xssfWorkbook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        }catch (Exception e){
            throw (e);
        }
    }
}
